<template>
  <side-bar-menu class="left-side-bar" ref="sideBarMenu">
    <div slot="header-title" class="left-side-bar__header">
      <span class="iconfont iconfont icon-xinxi"></span>
      <span class="left-side-bar__header--title">BOOM</span>
    </div>

    <div @click="toggleNavTab">
      <side-bar-item iconfont="icon-shezhi" name="首页" data-router="/home" />
      <side-bar-item iconfont="icon-shezhi" name="标题1" data-router="/test/1" />
      <side-bar-item iconfont="icon-shezhi" name="标题2" data-router="/test/2" />
      <div class="split-line"></div>
      <side-bar-item iconfont="icon-shezhi" name="消息" data-router="/test/3" />
      <side-bar-item iconfont="icon-shezhi" name="设置" data-router="/test/4" />
    </div>
  </side-bar-menu>
</template>

<script>
import { SideBarMenu, SideBarItem } from '../base/sidebar'
const ITEM_FOCUS_CLS = 'left-side-bar__item-bg'
const TARGET_CLS = 'side-bar-item'

export default {
  components: {
    SideBarMenu,
    SideBarItem
  },

  data() {
    return {
      lastTarget: ''
    }
  },

  mounted() {
    this.init()
  },

  methods: {
    init() {
      this.defaultSelectFirstItem()
    },

    /**
     * 默认选中第0项
     */
    defaultSelectFirstItem() {
      document.getElementsByClassName(TARGET_CLS)[0].click()
    },

    toggleNavTab(el) {
      let { target } = el

      // 事件委托有可能点击到里面的节点（图标，文字等），所以要找到最外层的节点。
      while (
        !target.getAttribute('class') ||
        !target.classList.contains(TARGET_CLS)
      ) {
        target = target.parentNode
      }

      // 移除上一个被点击节点的样式
      if (this.lastTarget) {
        if (this.lastTarget.getAttribute('class').includes(ITEM_FOCUS_CLS)) {
          this.lastTarget.classList.remove(ITEM_FOCUS_CLS)
        }
      }

      // 点击的tab添加背景颜色
      target.classList.add(ITEM_FOCUS_CLS)
      this.lastTarget = target

      // 点击相应的tab，跳转到对应的路由页面
      let dataRoute = target.getAttribute('data-router')
      dataRoute !== this.$route.fullPath && this.$router.push(dataRoute)
    },

    toggleSideBar() {
      this.$refs.sideBarMenu.toggleSideBar()
    }
  }
}
</script>

<style scoped>
.left-side-bar__header {
  display: inline-block;
}

.left-side-bar__header--title {
  margin-left: 10px;
  font-weight: bold;
}

.left-side-bar__item-bg {
  background-color: #87cefa;
}
</style>